package tbdp.tool.common;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by xbkaishui on 16/10/16.
 */
public class Config {

    private Logger log = Logger.getLogger(Config.class);

    private static Config conf = new Config();

    private Map<String, String> props = new HashMap<>();

    private Config() {
        loadConf();
    }

    private void loadConf() {
        File f = new File("./config/conf.properties");
        log.info("load conf from " + f.getAbsolutePath());
        if (f.exists()) {
            InputStream ins = null;
            try {
                ins = new FileInputStream(f);
                List<String> lines = IOUtils.readLines(ins);
                for (String line : lines) {
                    if (!line.startsWith("#")) {
                        String pair[] = line.split("=");
                        if (pair.length == 2) {
                            props.put(pair[0], pair[1].trim());
                        }
                    }
                }
            } catch (Exception e) {
                log.error("load file error!", e);
            } finally {
                IOUtils.closeQuietly(ins);
            }

            log.info("load conf " + this.props);
        }
    }

    public static Config getInstance() {
        return conf;
    }

    public String getProp(String key) {
        return props.get(key);
    }

    public Integer getPropAsInt(String key) {
        String val = getProp(key);
        if (StringUtils.isNotEmpty(val)) {
            return Integer.parseInt(val);
        }
        return null;
    }

    public int getThreads() {
        return getPropAsInt("threads");
    }

    public String getOutputDir() {
        return getProp("output");
    }
}
